package network;

import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.OutputStream;
import java.util.Comparator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import action.DataProcessAction;
import comparetor.CustomerComparetorByBirth;
import comparetor.CustomerComparetorById;
import pojo.Customer;

public class CmdAnalyserAndHandle{
	private Comparator<Customer> comparator;		
	private String format;
	private DataProcessAction da;
	
	public CmdAnalyserAndHandle() throws FileNotFoundException {
		format = "xml";
		comparator=new CustomerComparetorById();
		da = new DataProcessAction();
	}

	public boolean cmdAnalyseAndHandle(String cmd, OutputStream out) throws Exception {
		String r = "[LC] (xml|list) (id|birth)";
		Pattern p = Pattern.compile(r);
		Matcher m = p.matcher(cmd);
		
		if(!m.find()){
			if(cmd.equals("Q"))
				return false;
			
			out.write("you enter a wrong command\r\n".getBytes());
			return true;
		}
		String[] params = cmd.split(" ");
		format = params[1];
		if(params[2].equals("id")){
			comparator = new CustomerComparetorById();
		}
		else if(params[2].equals("birth")){
			comparator = new CustomerComparetorByBirth();
		}
		
		
		StringBuilder sb = da.action1(format, comparator);     //这里确定样式,返回输出的String
		
		if(params[0].equals("L")){
			//网络
			out.write((sb.toString()).replaceAll("\n", "\r\n").getBytes());
		}
		else if(params[0].equals("C")){
//			OutputStream o = new FileOutputStream("jordanTest.txt");
//			o.write(sb.toString().getBytes());
//			o.close();
            FileWriter fileWriter = new FileWriter("jordanTest.txt");  
            String s = new String(sb.toString());  
            fileWriter.write(s);  
            fileWriter.close(); // 关闭数据流  
			//文件
		}
		else if(params[0].equals("Q")){
			//退出
			return false;
		}
		return true;
	}
}
